<!-- 文章详情页 -->
<template>
  <div class="article-detail">
    <div class="article-container">
      <div class="article-header">
        <h1 class="article-title">{{ article.title }}</h1>
        <div class="article-meta">
          <div class="author-info">
            <el-avatar :size="40" :src="article.authorAvatar" />
            <div class="author-meta">
              <div class="author-name">{{ article.authorName }}</div>
              <div class="publish-time">{{ formatDateTime(article.createdAt) }}</div>
            </div>
          </div>
          
          <!-- 作者操作按钮 -->
          <div v-if="isAuthor" class="author-actions">
            <el-button type="primary" link @click="editArticle">
              编辑
            </el-button>
            <el-button type="danger" link @click="deleteArticle">
              删除
            </el-button>
          </div>
        </div>
      </div>

      <div class="article-content">
        <el-image 
          v-if="article.coverImage"
          :src="getImageUrl(article.coverImage)"
          class="cover-image"
          fit="cover"
        />
        <div class="content-text">{{ article.content }}</div>
      </div>

      <div class="article-actions">
        <div class="action-buttons">
          <el-button 
            :type="article.isLiked ? 'primary' : 'default'"
            @click="toggleLike"
          >
            <el-icon><Star /></el-icon>
            {{ article.likeCount }} 点赞
          </el-button>
        </div>
      </div>

      <!-- 评论区 -->
      <div class="comments-section">
        <h3>评论 ({{ article.commentCount }})</h3>
        
        <!-- 评论输入框 -->
        <div class="comment-input">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
          />
          <el-button 
            type="primary" 
            @click="submitComment"
            :loading="submitting"
          >
            发表评论
          </el-button>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <div 
            v-for="comment in comments" 
            :key="comment.id" 
            class="comment-item"
          >
            <div class="comment-user">
              <el-avatar :size="30" :src="comment.userAvatar" />
              <div class="comment-meta">
                <span class="comment-author">{{ comment.userName }}</span>
                <span class="comment-time">{{ formatDateTime(comment.createdAt) }}</span>
              </div>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
          </div>
        </div>

        <!-- 评论分页 -->
        <div v-if="comments.length > 0" class="comments-pagination">
          <el-pagination
            v-model:current-page="commentPage"
            v-model:page-size="commentSize"
            :total="commentTotal"
            layout="prev, pager, next"
            @current-change="fetchComments"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star } from '@element-plus/icons-vue'
import request from '@/utils/request'
import Cookies from 'js-cookie'

const route = useRoute()
const router = useRouter()
const userInfo = ref(JSON.parse(Cookies.get('userInfo') || '{}'))

const article = ref({})
const comments = ref([])
const commentContent = ref('')
const submitting = ref(false)
const commentPage = ref(1)
const commentSize = ref(10)
const commentTotal = ref(0)

const isAuthor = computed(() => article.value.userId === userInfo.value.id)

const getImageUrl = (fileName) => {
  if (!fileName) return ''
  return `${import.meta.env.VITE_API_URL}/api/file/download/${fileName}`
}

// 获取文章详情
const fetchArticle = async () => {
  try {
    console.log(route.params.id)
    const res = await request.get(`/article/${route.params.id}`)
    if (res.data) {
      article.value = res.data
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
    router.push('/community')
  }
}

// 获取评论列表
const fetchComments = async () => {
  try {
    const res = await request.get(`/article/${route.params.id}/comments`, {
      params: {
        page: commentPage.value,
        size: commentSize.value
      }
    })
    if (res.data) {
      comments.value = res.data.records
      commentTotal.value = res.data.total
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  submitting.value = true
  try {
    const res = await request.post(`/article/${route.params.id}/comment`, {
      content: commentContent.value.trim()
    })
    
    if (res.code === 200) {
      ElMessage.success('评论成功')
      commentContent.value = ''
      // 重新获取评论列表
      commentPage.value = 1
      await fetchComments()
      // 更新文章评论数
      article.value.commentCount++
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  } finally {
    submitting.value = false
  }
}

// 点赞/取消点赞
const toggleLike = async () => {
  try {
    const res = await request.post(`/article/${route.params.id}/like`)
    if (res.code === 200) {
      article.value.isLiked = !article.value.isLiked
      article.value.likeCount += article.value.isLiked ? 1 : -1
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 编辑文章
const editArticle = () => {
  router.push(`/community/article/edit/${route.params.id}`)
}

// 删除文章
const deleteArticle = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      type: 'warning'
    })
    
    const res = await request.delete(`/article/${route.params.id}`)
    if (res.code === 200) {
      ElMessage.success('文章已删除')
      router.push('/community')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除文章失败')
    }
  }
}

const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  })
}

onMounted(() => {
  fetchArticle()
  fetchComments()
})
</script>

<style scoped>
.article-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.article-container {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.article-header {
  margin-bottom: 30px;
}

.article-title {
  margin: 0 0 20px;
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-meta {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
}

.publish-time {
  font-size: 12px;
  color: #999;
}

.article-content {
  margin-bottom: 30px;
}

.cover-image {
  width: 100%;
  max-height: 400px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.content-text {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  white-space: pre-wrap;
}

.article-actions {
  border-top: 1px solid #eee;
  padding-top: 20px;
  margin-bottom: 30px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.comments-section {
  border-top: 1px solid #eee;
  padding-top: 30px;
}

.comments-section h3 {
  margin: 0 0 20px;
  font-size: 20px;
  font-weight: 500;
}

.comment-input {
  margin-bottom: 30px;
}

.comment-input .el-button {
  margin-top: 10px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.comment-user {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.comment-meta {
  display: flex;
  flex-direction: column;
}

.comment-author {
  font-size: 14px;
  font-weight: 500;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  margin-left: 40px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.comments-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 